import axios from 'axios';
import { useApartmentUserStoreHook } from '@/store/modules/apartmentUser';

// Create an axios instance with default config
const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // Needed for cookies/authentication
});

// Add interceptors for better error handling
api.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', {
      url: error.config?.url,
      method: error.config?.method,
      status: error.response?.status,
      data: error.response?.data,
      requestData: error.config?.data ? JSON.parse(error.config.data) : null
    });
    return Promise.reject(error);
  }
);

export interface Post {
  id: string;
  title: string;
  content: string;
  category: string;
  authorId: string;
  username: string;
  nickname: string;
  avatar: string;
  createdAt: Date;
  viewCount: number;
  commentCount: number;
  likeCount: number;
}

export interface CreatePostDto {
  title: string;
  content: string;
  category: string;
  authorId: string;
}

export interface UpdatePostDto {
  title?: string;
  content?: string;
  category?: string;
}

export interface PostsQueryParams {
  visible?: boolean;
  category?: string;
}

/**
 * Get all posts with optional filtering
 */
export const getPosts = async (params?: PostsQueryParams): Promise<Post[]> => {
  try {
    const response = await api.get('/discussion-posts', { params });
    return response.data;
  } catch (error) {
    console.error('Error fetching posts:', error);
    throw error;
  }
};

/**
 * Get a single post by ID
 */
export const getPost = async (id: string): Promise<Post> => {
  try {
    console.log(`Fetching post with ID: ${id}`);
    const response = await api.get(`/discussion-posts/${id}`);
    console.log(`Received post data:`, response.data);
    return response.data;
  } catch (error) {
    console.error(`Error fetching post ${id}:`, error);
    if (error.response) {
      console.error('Response status:', error.response.status);
      console.error('Response data:', error.response.data);
    }
    throw error;
  }
};

/**
 * Create a new post
 */
export const createPost = async (postData: CreatePostDto): Promise<Post> => {
  try {
    // Validate the user ID before sending
    if (!postData.authorId) {
      throw new Error('Author ID is required');
    }
    
    console.log('Sending post creation request:', postData);
    const response = await api.post('/discussion-posts', postData);
    return response.data;
  } catch (error) {
    console.error('Error creating post:', error);
    throw error;
  }
};

/**
 * Update an existing post
 */
export const updatePost = async (id: string, postData: UpdatePostDto): Promise<Post> => {
  try {
    const response = await api.patch(`/discussion-posts/${id}`, postData);
    return response.data;
  } catch (error) {
    console.error(`Error updating post ${id}:`, error);
    throw error;
  }
};

/**
 * Delete a post
 */
export const deletePost = async (id: string): Promise<void> => {
  try {
    await api.delete(`/discussion-posts/${id}`);
  } catch (error) {
    console.error(`Error deleting post ${id}:`, error);
    throw error;
  }
};

/**
 * Like a post
 */
export const likePost = async (id: string): Promise<Post> => {
  try {
    const response = await api.post(`/discussion-posts/${id}/like`);
    return response.data;
  } catch (error) {
    console.error(`Error liking post ${id}:`, error);
    throw error;
  }
};

/**
 * Get all posts by a specific author/user
 */
export const getPostsByAuthor = async (authorId: string): Promise<Post[]> => {
  try {
    const response = await api.get(`/discussion-posts/by-author/${authorId}`);
    return response.data;
  } catch (error) {
    console.error(`Error fetching posts for author ${authorId}:`, error);
    throw error;
  }
};

/**
 * Get all posts for the currently logged in user
 */
export const getCurrentUserPosts = async (): Promise<Post[]> => {
  try {
    const apartmentUserStore = useApartmentUserStoreHook();
    const userId = apartmentUserStore.userId;
    return getPostsByAuthor(userId);
  } catch (error) {
    console.error('Error fetching current user posts:', error);
    throw error;
  }
};

/**
 * Get recent posts with comments
 * Useful for notifications
 */
export const getRecentPostsWithComments = async (limit: number = 5): Promise<Post[]> => {
  try {
    const response = await api.get('/discussion-posts', { 
      params: { 
        limit, 
        sort: 'createdAt:DESC',
        'filter[commentCount][gt]': 0 // 只获取有评论的帖子
      } 
    });
    return response.data;
  } catch (error) {
    console.error('Error fetching recent posts with comments:', error);
    return []; // 返回空数组而不是抛出错误
  }
};

export default {
  getPosts,
  getPost,
  createPost,
  updatePost,
  deletePost,
  likePost,
  getPostsByAuthor,
  getCurrentUserPosts,
  getRecentPostsWithComments
}; 